<template>
  <div class="content container-fluid report-list" v-show="!!columns && columns.length>0">
    <div class="portlet">
      <!-- 工具栏 -->
      <div v-if="!isAdmin" class="tools flex-align-items flex-between reports-tools-flex">
        <div class="tools-l">
          <a-select :value="type" style="width: 120px" @change="handleChangeType">
            <a-select-option value=" ">ALL</a-select-option>
            <a-select-option value="creative">Creative</a-select-option>
            <a-select-option value="campaigns">Campaigns</a-select-option>
          </a-select>&nbsp;&nbsp;&nbsp;
          <a-select :value="typeId" style="width: 250px;" showSearch @change="changeTypeCre">
            <a-select-option
              v-for="(item, key) in getTypeList"
              :key="key"
              :value="item.id"
            >{{item.value}}</a-select-option>
          </a-select>
        </div>
        <!-- 暂时隐藏 -->
        <div class="tools-r flex-align-items" v-if="1==2">
          <!-- start 导出数据表 -->
          <a-dropdown style="margin-right: 1rem">
            <a-menu slot="overlay" @click="handleExportClick">
              <a-menu-item key="excel">
                <a-icon type="file-excel" />excel
              </a-menu-item>
              <a-menu-item key="pdf">
                <a-icon type="file-pdf" />pdf
              </a-menu-item>
              <a-menu-item key="word">
                <a-icon type="file-word" />word
              </a-menu-item>
            </a-menu>
            <a-button style="margin-left: 8px">
              Export
              <a-icon type="down" />
            </a-button>
          </a-dropdown>
        </div>
      </div>

      <!-- table列表 and 分页 -->
      <div class="bottom-table-page">
        <!-- 表格数据 -->
        <a-table
          :columns="columns"
          :rowKey="record => record.id"
          :dataSource="dataList"
          :loading="listLoading"
          :pagination="false"
          :scroll="{ x: 1000 }"
        >
          <template
            slot="prepay"
            slot-scope="prepay"
          >{{ prepay == 1 ? 'Yes' : prepay == 0 ? 'No' : ' -- ' }}</template>

          <template slot="campaignsName" slot-scope="campaignsName, row">
            {{ campaignsName }}
            <router-link
              v-show="row.campaignsId !== ' -- '"
              :to="{ path: '/bidder/editcampaign/id/'+ row.campaignsId}"
            >#{{row.campaignsId}}</router-link>
          </template>

          <template slot="creativeName" slot-scope="creativeName, row">
            {{ creativeName }}
            <a
              v-show="row.creativeId !== ' -- '"
              href="javascript:;"
              @click="editcreative(row)"
            >#{{row.creativeId}}</a>
          </template>

          <template
            slot="name"
            slot-scope="name, row"
          >{{ row.firstName}} {{row.lastName}} # {{row.userId}}</template>
        </a-table>

        <!-- 分页 暂时隐藏-->
        <div class="public-page-box" v-if="false">
          <a-pagination
            showSizeChanger
            showQuickJumper
            :pageSize.sync="pagination.pageSize"
            :total="pagination.total"
            v-model="pagination.current"
            @change="onShowSizeChange"
            @showSizeChange="onShowSizeChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getReportTable } from "../../../api";
import { getCampaignsList } from "../../../api/pulldown-data";
import { parseTime } from "../../../utils/time";

export default {
  name: "ReportList",
  filters: {
    timeDate(v) {
      return parseTime(v, "{y}-{m}-{d}");
    }
  },
  data() {
    return {
      columns: [],
      listLoading: false,

      plainOptions: null, //导出配置功能组
      defaultCheckedArray: [], //导出配置功能组
      dataList: [],

      pagination: {
        pageSizeOptions: ["10", "20", "30", "40", "50"],
        current: 1,
        pageSize: 10,
        total: 500
      },
      typeList: [],
      type: " ",
      typeId: ""
    };
  },
  computed: {
    getTypeList() {
      let arr = this.typeList.map(item => {
        return {
          id: item.id,
          value: `ID#${item.id} | ${item.name}`
        };
      });
      arr.unshift({ id: "", value: "ALL" });
      return arr;
    }
  },
  props: {
    dateStage: {
      type: Object,
      required: false
    },
    isAdmin: {
      type: Boolean,
      default: false
    },
    parentTable: {
      type: Array,
      required: false
    }
  },
  watch: {
    "dateStage.time"() {
      this.typeFetch({ id: this.id, type: this.type, ...this.dateStage });
    },
    type(v) {
      this.findByTypeList(v);
    },
    parentTable(v) {
      this.tableFormat(v);
    }
  },
  methods: {
    //跳转到对应的广告系列编辑页
    editcreative(record) {
      record.id = record.campaignsId;
      record.name = record.campaignsName;
      this.$store.commit("changeCampaigns", record);
      this.$router.push("/bidder/editcreative/creativeid/" + record.creativeId);
    },

    changeTypeCre(id) {
      this.typeId = id;
      this.typeFetch({ id, type: this.type });
    },
    handleChangeType(type) {
      this.type = type;
    },

    handleExportClick(e) {
      console.log(e);
    },

    //监听分页的变化
    onShowSizeChange(page, pageSize) {
      console.log(page, pageSize);
      this.pagination.pageSize = pageSize;
      this.pagination.current = page;
    },

    getCampaignType() {
      getCampaignsList(this.type).then(res => {
        let { code, data } = res.data;
        if (code == "200") {
          this.typeList = data;
        }
      });
    },

    //table 表单拉取数据
    initFetch() {
      let { type } = this.$route.params;
      this.type = type === "index" ? " " : type || "";
      if (this.type === " ") {
        this.findByTypeList(this.type);
      }
    },

    typeFetch(params) {
      //查询前开始动画
      this.listLoading = true;
      getReportTable(params)
        .then(res => {
          let { code, data } = res.data || {};
          if (code == "200" && data.length > 0) {
            this.tableFormat(data);
          }
        })
        .finally(() => {
          this.listLoading = false;
        });
    },

    findByTypeList(v) {
      let { id } = this.$route.params;
      this.typeList = [];
      let params = { type: v };
      if (id != 0) {
        params.id = id;
      }
      this.typeFetch(params);

      //查询类型集合
      if (!!v.trim()) {
        this.getCampaignType();
      }
    },

    /***
     * 动态table 数据展示处理
     * @param data
     */
    tableFormat(data) {
      this.dataList = [];

      let thList = data; //table渲染需要的数据
      let ths = []; //自定义表头
      let endTotal = {}; //最后一排统计

      //更加返回的数据 自定义包头且分配顺序 (动态表头)
      for (let key of Object.keys(thList[0])) {
        //如找到以下条件字段 则不往表头里添加
        if (key === "id" || key === "campaignsId" || key === "creativeId") {
          continue;
        }
        if (key === "firstName" || key === "lastName" || key === "userId") {
          if (
            !!ths.find(item => {
              return item.title == "name";
            })
          ) {
            continue;
          }
          ths.push({
            title: "name",
            dataIndex: "name",
            scopedSlots: { customRender: "name" }
          });
        }
        ths.push({
          title: key,
          dataIndex: key,
          scopedSlots: { customRender: key }
        });
      }
      //把找到日期删除并返回 放在第一位显示
      let thDate = ths.filter((item, index) => {
        if (item.title == "dateStats") {
          ths.splice(index, 1);
          return item;
        }
      });
      ths.unshift(thDate[0]);
      this.columns = ths;

      //计算最后一排总和
      thList = thList.map((item, index) => {
        item.dateStats = parseTime(item.dateStats, "{y}-{m}-{d}");
        for (let [key1, value1] of Object.entries(item)) {
          switch (key1) {
            case "dateStats":
              endTotal[key1] = "Total";
              break;
            case "id":
              endTotal[key1] = " - ";
              break;
            case "campaignsName":
              endTotal[key1] = " - ";
              break;
            case "creativeName":
              endTotal[key1] = " - ";
              break;
            case "campaignsId":
              endTotal[key1] = " - ";
              break;
            case "creativeId":
              endTotal[key1] = " - ";
              break;
            case "firstName":
              endTotal[key1] = " - ";
              break;
            case "lastName":
              endTotal[key1] = " - ";
              break;
            case "prepay":
              endTotal[key1] = " - ";
              break;
            case "userId":
              endTotal[key1] = " - ";
              break;
            default:
              if (index == 0) {
                endTotal[key1] = value1;
              } else {
                endTotal[key1] += value1;
              }
              endTotal[key1] = Math.floor(endTotal[key1] * 1000) / 1000;
          }
        }
        item.winsPrice = Math.floor(item.winsPrice * 1000) / 1000;
        return item;
      });

      thList.push(endTotal);
      this.dataList = thList;
    }
  },
  created() {
    if (!this.isAdmin) {
      this.initFetch();
    }
  }
};
</script>

<style lang="less">
.ant-popover-buttons {
  text-align: left;
}
.ant-popover-inner {
  max-width: 70%;
}
.field-add-box {
  left: 80px !important;
  .ant-popover-content {
    .ant-popover-message-title {
      padding-left: 8px !important;
    }
    .ant-popover-buttons button:nth-child(1) {
      display: none;
    }
  }
}

.field-child {
  z-index: 1040;
  .ant-tooltip-content {
    .ant-tooltip-inner {
      background-color: #fff !important;
      width: 20rem;
    }
    .ant-tooltip-arrow {
      border-bottom-color: #fff;
    }
  }
}
/* 动态显示已选添加组区域 111 */
.nav-condition {
  width: 100%;
  height: auto;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  padding-bottom: 10px;
  .nav-item {
    font-size: 1.5rem;
    color: @primary-color;
    margin-right: 0.65rem;
    position: relative;
    cursor: pointer;
    .nav-item-name {
      padding-left: 0.3rem;
    }
    .nav-item-name:hover {
      border-bottom: 1px solid @primary-color;
    }
  }
}

.reports-tools-flex {
  .ant-form-item {
    margin-bottom: 0;
  }
  .tools-l {
    display: flex;
  }
}

@media screen and (max-width: 768px) {
  .reports-tools-flex {
    display: block;
    .tools-l {
      margin-bottom: 10px;
    }
    .tools-r {
      justify-content: flex-end;
    }
  }
}
@media screen and (max-width: 640px) {
  .reports-tools-flex {
    .tools-r {
      display: grid;
      grid-template-columns: 100%;
      grid-template-rows: repeat(4, auto);
      grid-gap: 5px;
    }
  }
}
.report-list {
  .bottom-table-page {
    .ant-table-body {
      .ant-table-fixed {
        .ant-table-tbody {
          tr:nth-last-child(1) {
            font-weight: bold;
          }
        }
      }
    }
  }
}
</style>
